#!/usr/bin/env python3
"""
完整系统测试脚本
"""

import requests
import json
import sys
import os
import random
import time
from pathlib import Path

def check_backend_service():
    """检查后端服务"""
    print("[SEARCH] 检查后端服务...")
    
    try:
        response = requests.get("http://localhost:8080/", timeout=5)
        if response.status_code == 200:
            print("[PASS] 后端服务正常运行")
            return True
        else:
            print(f"[FAIL] 后端服务响应异常: {response.status_code}")
            return False
    except Exception as e:
        print(f"[FAIL] 后端服务未启动: {e}")
        print("   请先启动后端服务: python app.py")
        return False

def upload_sample_logs():
    """上传示例日志文件"""
    print("📤 上传示例日志文件...")
    
    sample_file = "sample_logs.tar.gz"
    if not os.path.exists(sample_file):
        print(f"[FAIL] 示例文件 {sample_file} 不存在")
        return False
    
    try:
        with open(sample_file, 'rb') as f:
            files = {'file': (sample_file, f, 'application/gzip')}
            response = requests.post("http://localhost:8080/upload", files=files, timeout=30)
        
        if response.status_code == 200:
            result = response.json()
            print(f"[PASS] 示例日志上传成功")
            print(f"   总日志数: {result.get('total_logs', 0)}")
            return True
        else:
            print(f"[FAIL] 示例日志上传失败: {response.status_code}")
            print(f"   错误信息: {response.text}")
            return False
    except Exception as e:
        print(f"[FAIL] 示例日志上传失败: {e}")
        return False

def test_basic_analysis():
    """测试基础分析功能"""
    print("[SEARCH] 测试基础分析功能...")
    
    try:
        response = requests.get("http://localhost:8080/analysis", timeout=10)
        if response.status_code == 200:
            result = response.json()
            print("[PASS] 基础分析功能正常")
            print(f"   总日志数: {result.get('total_logs', 0)}")
            print(f"   组件数量: {result.get('unique_components', 0)}")
            return True
        else:
            print(f"[FAIL] 基础分析失败: {response.status_code}")
            return False
    except Exception as e:
        print(f"[FAIL] 基础分析失败: {e}")
        return False

def test_error_categories():
    """测试错误分类功能"""
    print("[SEARCH] 测试错误分类功能...")
    
    try:
        response = requests.get("http://localhost:8080/ai/error-categories", timeout=10)
        if response.status_code == 200:
            categories = response.json()
            print(f"[PASS] 错误分类功能正常")
            print(f"   找到 {len(categories)} 个错误分类:")
            for category in categories:
                print(f"   - {category['name']}: {category['count']} 条日志")
            return categories
        else:
            print(f"[FAIL] 错误分类失败: {response.status_code}")
            return []
    except Exception as e:
        print(f"[FAIL] 错误分类失败: {e}")
        return []

def test_ai_config():
    """测试AI配置功能"""
    print("[SEARCH] 测试AI配置功能...")
    
    try:
        response = requests.get("http://localhost:8080/ai/config", timeout=10)
        if response.status_code == 200:
            config = response.json()
            print("[PASS] AI配置功能正常")
            print(f"   提供商: {config.get('provider', 'unknown')}")
            print(f"   模型: {config.get('model', 'unknown')}")
            return True
        else:
            print(f"[FAIL] AI配置获取失败: {response.status_code}")
            return False
    except Exception as e:
        print(f"[FAIL] AI配置获取失败: {e}")
        return False

def test_overview_analysis():
    """测试概览分析"""
    print("[SEARCH] 测试概览分析...")
    
    try:
        response = requests.post("http://localhost:8080/ai/analyze", json={}, timeout=60)
        
        if response.status_code == 200:
            result = response.json()
            if 'initial_analysis' in result:
                print("[PASS] 概览分析成功")
                print(f"   分析结果长度: {len(result['initial_analysis'])} 字符")
                return True
            else:
                print("[FAIL] 概览分析结果异常")
                return False
        else:
            print(f"[FAIL] 概览分析失败: {response.status_code}")
            print(f"   错误信息: {response.text}")
            return False
    except Exception as e:
        print(f"[FAIL] 概览分析失败: {e}")
        return False

def test_error_type_analysis(category_name):
    """测试特定错误类型分析"""
    print(f"[SEARCH] 测试 {category_name} 错误分析...")
    
    try:
        data = {"error_category": category_name}
        response = requests.post("http://localhost:8080/ai/analyze", json=data, timeout=60)
        
        if response.status_code == 200:
            result = response.json()
            if 'initial_analysis' in result:
                print("[PASS] 错误类型分析成功")
                print(f"   错误类型: {result.get('error_category', category_name)}")
                print(f"   错误数量: {result.get('error_count', 0)}")
                print(f"   分析结果长度: {len(result['initial_analysis'])} 字符")
                return True
            else:
                print("[FAIL] 错误类型分析结果异常")
                return False
        else:
            print(f"[FAIL] 错误类型分析失败: {response.status_code}")
            print(f"   错误信息: {response.text}")
            return False
    except Exception as e:
        print(f"[FAIL] 错误类型分析失败: {e}")
        return False

def test_ai_question():
    """测试AI问答功能"""
    print("[SEARCH] 测试AI问答功能...")
    
    try:
        question = "请简单介绍一下这个日志分析系统"
        data = {"question": question}
        response = requests.post("http://localhost:8080/ai/ask", json=data, timeout=60)
        
        if response.status_code == 200:
            result = response.json()
            if 'answer' in result:
                print("[PASS] AI问答功能成功")
                print(f"   回答长度: {len(result['answer'])} 字符")
                return True
            else:
                print("[FAIL] AI问答结果异常")
                return False
        else:
            print(f"[FAIL] AI问答失败: {response.status_code}")
            print(f"   错误信息: {response.text}")
            return False
    except Exception as e:
        print(f"[FAIL] AI问答失败: {e}")
        return False

def main():
    """主测试函数"""
    print("[TEST] 完整系统测试")
    print("=" * 50)
    
    # 检查后端服务
    if not check_backend_service():
        sys.exit(1)
    
    # 上传示例日志文件
    if not upload_sample_logs():
        print("\n[FAIL] 示例日志上传失败，无法继续测试")
        sys.exit(1)
    
    # 等待一下让系统处理日志
    print("[WAIT] 等待系统处理日志...")
    time.sleep(2)
    
    # 测试基础分析功能
    if not test_basic_analysis():
        print("\n[FAIL] 基础分析功能测试失败")
        sys.exit(1)
    
    # 测试AI配置
    if not test_ai_config():
        print("\n[WARN]  AI配置测试失败，但继续其他测试")
    
    # 测试错误分类
    categories = test_error_categories()
    if not categories:
        print("\n[FAIL] 错误分类测试失败")
        sys.exit(1)
    
    # 测试概览分析
    if not test_overview_analysis():
        print("\n[WARN]  概览分析测试失败，但继续其他测试")
    
    # 随机选择一个错误类型进行详细分析
    if categories:
        random_category = random.choice(categories)['name']
        print(f"🎲 随机选择错误类型: {random_category}")
        if not test_error_type_analysis(random_category):
            print("\n[WARN]  错误类型分析测试失败，但继续其他测试")
    
    # 测试AI问答
    if not test_ai_question():
        print("\n[WARN]  AI问答测试失败")
    
    print("\n" + "=" * 50)
    print("[SUCCESS] 完整系统测试完成!")
    print("\n[STATS] 测试结果:")
    print("   [PASS] 后端服务: 正常")
    print("   [PASS] 日志上传: 成功")
    print("   [PASS] 基础分析: 正常")
    print("   [PASS] 错误分类: 正常")
    print("   [PASS] AI功能: 可用")
    print("\n[START] 系统已准备就绪，可以开始使用!")

if __name__ == "__main__":
    main() 